<html>
<head>
	<title>Greatiful App</title>
	<link rel="stylesheet" href="style/style.css" type="text/css">
	<script src="js/jquery.js"></script>
	<!--	Uncomment to Simplify debugging
	<script type="text/javascript" src="js/chrome_ex_oauthsimple.js"></script>
    <script type="text/javascript" src="js/chrome_ex_oauth.js"></script>    
	-->
</head>
<body>
	<div id='body'>
		<div id='header'>Chromed Crown</div>
		<div class='top-menu'>
			<ul>  
				<li><a id="subscriberListLink" href="#" alt="List My Channels" onclick="subscriber.list(); return false;">My Channels</a></li>
				<li><a id="channelListLink" href="#" alt="List All Channels" onclick="channel.list(); return false;">All Channels</a></li>				
  				<li><a href="#" alt="Logout" onclick="util.logout(); return false;">Logout</a></li>
			</ul>
		</div>
		<div id='pageTitle'></div>
		<div id='container'></div>
		<div id='footer'>
			<div class='grayText'>
				<a class='grayText' href='http://code.google.com/p/chromedcrown/' onclick="util.runLink(this); return false;">Chromed Crown</a> - 
				<a class='grayText' href='http://code.google.com/p/chromedcrown/issues/list' onclick="util.runLink(this); return false;">Issues</a> -
				&copy;2011 Denis Tukalenko
			</div>
			<div id='status' class='noError'>Loading...</div>
		</div>		
	</div>
	
<script><!--

	//Protected namespaces.
	var util = {};
	var channel = {};
	var subscriber = {};
	var user = {};

	//Constants
	const ERR_TIMEOUT = 'Timeout. Please try again later';
	const ERR_BADGATEWAY = 'Bad Gateway. Please try again later';
	const ERR_OTHER = 'Unknown Error. Please try again later';
	
	const TIMEOUT_VALUE = 5000;
	
	const DEFAULT_PREVIEW_IMG_PATH = 'img/no_preview.png';
	
	var requestFailureCount = 0;  // used for exponential backoff
	var pollIntervalMax = 1000 * 60 * 60;  // 1 hour
	var authorised = false;	//	call all API with OAuth 		
	
	var channelsLinkHtml = "<span><a href='' onclick='channel.list(); return false;'>Channels</a></span>";
	var bgPage = chrome.extension.getBackgroundPage();		
	bgPage.setBadge('5');
	
	
	/**
	*	Get channels list divided by pages.
	*	http://greatiful.com/api/doc/method/4/	
	*/
	channel.list = function() {		
		
		util.showLoading();
		
		$(".activeMenuItem").removeClass("activeMenuItem");
		$("#channelListLink").addClass("activeMenuItem");
		
		if (!authorised) {
			//	Small hack due to Chromium bug. I think so =)
			//	Bug: craches when loading this method after authorisation - fails to close auth tab
			try {
				var timer = setTimeout("util.showError(ERR_TIMEOUT)",TIMEOUT_VALUE);	
			} catch (err) {
				console.log(err);
			}
			
			var url = "http://greatiful.com/api/channels/list.json?callback=?";		
			$.getJSON(url, function(r) {
				$("#status").hide();
				if (r.status == 'OK') {					
					clearTimeout(timer);
					util.clearPage();
					
					requestFailureCount = 0;
					
					$('#pageTitle').append(channelsLinkHtml);
					var tmphtml = '';
					var imghtml = '';				
					var	length = r.data.channels.length;
					for (i=0;i<length;i++) {
						console.log(r.data.channels[i]);
						
						if (r.data.channels[i].image != undefined) {
							imghtml = '<img height="50" width="50" src="'+r.data.channels[i].image.url+'"/>';
						} else {
							imghtml = '<img height="50" width="50" src="'+DEFAULT_PREVIEW_IMG_PATH+'"/>';
						}
						
						tmphtml += '<div class="item" onclick="channel.items('+r.data.channels[i].id+');">'+
									'<div style="float:left;">'+imghtml+'</div>'+
									'<div style="margin:0px 0px 0px 55px">' +
										'<div><h3><a>'+r.data.channels[i].title+'</a></h3></div>'+
										'<div>'+r.data.channels[i].description+'</div>'+
									'</div>'+
									'<div style="clear:both;"></div>' +
								'</div>';						
					}
					$('#container').append(tmphtml);					
					//util.setContainerHeight();
				}
			});
			
		} else {
			
			var url = "http://greatiful.com/api/channels/list.json";
			var request = {
				'method': 'GET',			
				'headers': bgPage.oauth.getAuthorizationHeader(url, 'GET')
			};
			var receiveList =  function (r, xhr) {							
				if (xhr.status == 200) {
					$("#status").hide();
					requestFailureCount = 0
					
					util.clearPage();								
					
					$('#pageTitle').append(channelsLinkHtml);
					var tmphtml = '';
					var imghtml = '';				
					var	length = r.data.channels.length;
					for (i=0;i<length;i++) {
						console.log(r.data.channels[i]);
						
						if (r.data.channels[i].image != undefined) {
							imghtml = '<img height="50" width="50" src="'+r.data.channels[i].image.url+'"/>';
						} else {
							imghtml = '<img height="50" width="50" src="'+DEFAULT_PREVIEW_IMG_PATH+'"/>';
						}
						
						tmphtml = '<div class="item" onclick="channel.items('+r.data.channels[i].id+');">'+
									'<div style="float:left;">'+imghtml+'</div>'+
									'<div style="margin:0px 0px 0px 55px">' +
										'<div><h3><a>'+r.data.channels[i].title+'</a></h3></div>'+
										'<div>'+r.data.channels[i].description+'</div>'+
									'</div>'+
									'<div style="clear:both;"></div>' +
								'</div>';
						$('#container').append(tmphtml);
					}
				} else {
					console.log(xhr.response);
					util.showError(xhr.statusText);				
				}		
			}
		}
												
		bgPage.oauth.sendSignedRequest(url, receiveList, request);
	}

	
	
	channel.items = function(channelID) {
		util.showLoading();
		var url = "http://greatiful.com/api/channels/"+channelID+"/items.json?preview_only=true&callback=?";
		var t = setTimeout("util.showError(ERR_TIMEOUT)",TIMEOUT_VALUE);
		$.getJSON(url, function(r) {
			$("#status").hide();
			if (r.status == 'OK') {
				clearTimeout(t);
				util.clearPage();
				
				requestFailureCount = 0;
				
				$('#pageTitle').append(channelsLinkHtml+' - <span>'+r.data.title+'</span>');
				
				var tmphtml = '';
				
				if (r.data.image != undefined) {
					imghtml = '<img height="50" width="50" src="'+r.data.image.url+'"/>';
				} else {
					imghtml = '<img height="50" width="50" src="'+DEFAULT_PREVIEW_IMG_PATH+'"/>';
				}
				
				for (i=0;i<r.data.items.length;i++) {
					tmphtml = '<div class="item" onclick="channel.runItem('+r.data.items[i].id+');">'+
								'<div style="float:left;">'+imghtml+'</div>'+
								'<div style="margin:0px 0px 0px 55px">' +
									'<div><h3><a>'+r.data.items[i].title+'</a></h3></div>'+
									'<div>'+r.data.items[i].description+'</div>'+
								'</div>'+
								'<div style="clear:both;"></div>' +
							'</div>';
					$('#container').append(tmphtml);
				}
			}
		});		
	}

	
	
	channel.runItem = function(itemID) {
		chrome.tabs.create({'url': 'http://greatiful.com/reader/?i='+itemID});
	}

	
	
	util.clearPage = function () {
		$('#container').empty();
		$('#pageTitle').empty();
	}
	
	
	
	subscriber.list = function () {		
		util.showLoading();
		$(".activeMenuItem").removeClass("activeMenuItem");
		$("#subscriberListLink").addClass("activeMenuItem");
		
		var url = "http://greatiful.com/api/reader/list.json";
		var request = {
			'method': 'GET',			
			'headers': bgPage.oauth.getAuthorizationHeader(url, 'GET')
		};
		var receiveList =  function (r, xhr) {							
			if (xhr.status == 200) {
				$("#status").hide();
				requestFailureCount = 0
			} else {				
				util.showError(xhr.statusText);				
			}		
		}
		
		bgPage.oauth.sendSignedRequest(url, receiveList, request);				
	}			
	
	
	
	util.logout = function() {          
		bgPage.oauth.clearTokens();
		window.close();
    };
	
	
    
    util.showLoading = function() {
    	$('#status').text('Loading...').removeClass('error').addClass('noError').show();
    }
    
    
    
	util.showError = function (reason) {
		$('#status').text(reason).removeClass('noError').addClass('error').show();
		setTimeout("$('#status').removeClass('error').addClass('noError').hide()", 5000);
		++requestFailureCount;
	}
	
	
	
	util.runLink = function(link) {		
		chrome.tabs.create({'url': link.href});
	}
	
	
	
	util.scheduleRequest = function() {
		var exponent = Math.pow(2, requestFailureCount);
		var delay = Math.min(bgPage.pollIntervalMin * exponent, pollIntervalMax);
		delay = Math.round(delay);
		  
		if (bgPage.oauth.hasToken()) {
		    var req = bgPage.window.setTimeout(function() {
		      subscriber.list();
		      util.scheduleRequest();
		    }, delay);
		    bgPage.requests.push(req);
		  }	
	}
	
	
	
	user.info = function () {			
		var url = "http://greatiful.com/api/user/info.json";
		var request = {
			'method': 'GET',			
			'headers': bgPage.oauth.getAuthorizationHeader(url, 'GET')
		};
		var receiveInfo = function(r, xhr) {			
			if (xhr.status == 200) {
				$("#status").hide();
				requestFailureCount = 0;				
			} else {				
				util.showError(xhr.statusText);
			}		
		}
		
		bgPage.oauth.sendSignedRequest(url, receiveInfo, request);				
	}	
	
	
	
	util.setContainerHeight = function() {		
		console.log(window.innerHeight);
		//var height = window.innerHeight - 65 - 16; // 25 for header, 10 for footer
		var height = window.innerHeight - 65-16; // 25 for header, 10 for footer
		$('#container').css('height',height+'px');
	}
			
	
	
	bgPage.oauth.authorize(function() {				
		subscriber.list();
		user.info();
		util.scheduleRequest();
	});
	
</script>

</body>
</html>
